package exsun.jt808.data.util.parse;

import java.nio.charset.Charset;

public class DecoderUtils {

	public static final String string_encoding = "GBK";

	public static final Charset string_charset = Charset.forName(string_encoding);

	public DecoderUtils() {
	}

	public static String parseStringFromBytes(byte[] data) {
		return new String(data, string_charset);
	}

	public static String parseStringFromBytes(byte[] data, int startIndex, int lenth) {
		return parseStringFromBytes(data, startIndex, lenth, null);
	}

	public static String parseStringFromBytes(byte[] data, int startIndex, int lenth,
			String defaultVal) {
		try {
			byte[] tmp = new byte[lenth];
			System.arraycopy(data, startIndex, tmp, 0, lenth);
			return new String(tmp, string_charset);
		} catch (Exception e) {
			e.printStackTrace();
			return defaultVal;
		}
	}

	public static String parseBcdStringFromBytes(byte[] data, int startIndex, int lenth) {
		return parseBcdStringFromBytes(data, startIndex, lenth, null);
	}

	public static String parseBcdStringFromBytes(byte[] data, int startIndex, int lenth,
			String defaultVal) {
		try {
			byte[] tmp = new byte[lenth];
			System.arraycopy(data, startIndex, tmp, 0, lenth);
			return BCD8421Operater.bcd2String(tmp);
		} catch (Exception e) {
			e.printStackTrace();
			return defaultVal;
		}
	}

	public static int parseIntFromBytes(byte[] data, int startIndex, int length) {
		return parseIntFromBytes(data, startIndex, length, 0);
	}

	public static int parseIntFromBytes(byte[] data, int startIndex, int length, int defaultVal) {
		try {
			// 字节数大于4,从起始索引开始向后处理4个字节,其余超出部分丢弃
			final int len = length > 4 ? 4 : length;
			byte[] tmp = new byte[len];
			System.arraycopy(data, startIndex, tmp, 0, len);
			return BitOperator.byteToInteger(tmp);
		} catch (Exception e) {
			e.printStackTrace();
			return defaultVal;
		}
	}

	public static byte[] byteCopy(byte[] data, int startIndex, int size) {
		byte[] tmp = new byte[size];
		System.arraycopy(data, startIndex, tmp, 0, size);
		return tmp;
	}

	public static byte[] byteCopy(byte[] data, int startIndex, int length, int size) {
		byte[] tmp = new byte[size];
		System.arraycopy(data, startIndex, tmp, 0, length);
		return tmp;
	}

	public static long fourBytesToLong(byte[] data, int startIndex) {
		try {
			byte[] tmp = new byte[4];
			System.arraycopy(data, startIndex, tmp, 0, 4);
			return BitOperator.fourBytesToLong(tmp);
		} catch (Exception e) {
			e.printStackTrace();
			return 0L;
		}
	}
}
